// pages/orderDetail/orderDetail.js
Page({
  data: {
    orderId: "", // 订单 ID
    cart: [], // 订单商品
    totalAmount: "0.00", // 订单总金额
    shippingFee: "包邮", // 运费
    couponStatus: "无可用", // 优惠券状态
    giftCardStatus: "无可用", // 礼品卡状态
    address: {}, // 订单地址信息
    time: "未支付", // 付款时间
    publishedAt: "未知", // 下单时间
    state: "待处理", // 订单状态
    au: "", // 订单人
    steps: [
      { desc: "已付款" },
      { desc: "待发货" },
      { desc: "待收货" },
      { desc: "退款/售后" },
    ],
  },

  onLoad(options) {
    console.log("订单详情页收到的参数:", options);

    if (!options.orderId) {
      wx.showToast({ title: "订单ID缺失", icon: "error" });
      return;
    }

    this.setData({ orderId: options.orderId });
    this.fetchOrderDetail(options.orderId);
  },

  fetchOrderDetail(orderId) {
    wx.request({
      url: "http://localhost:3000/api/selectOrder",
      method: "POST",
      data: { filterQuery: { _id: orderId } }, // 传递订单 ID
      success: (res) => {
        console.log("订单详情返回数据：", res.data);

        if (res.data.code === 200 && res.data.list.length > 0) {
          const order = res.data.list[0];

          // 根据订单状态 state 设置 actnum
        let actnum = 0; // 默认是已付款
        switch (order.state) {
          case "待发货":
            actnum = 1;
            break;
          case "待收货":
            actnum = 2;
            break;
          case "退款/售后":
            actnum = 3;
            break;
        }

          this.setData({
            cart: order.orderItems || [], // **确保 cart 正确赋值**
            totalAmount: order.totalAmount || "0.00",
            shippingFee: order.shippingFee || "包邮",
            couponStatus: order.couponStatus || "无可用",
            giftCardStatus: order.giftCardStatus || "无可用",
            address: order.address || {}, // 地址
            time: order.time || "未支付",
            publishedAt: order.publishedAt || "未知",
            state: order.state || "待处理",
            au: order.au || "未知用户", // 订单人
            phone:order.phone,
            actnum: actnum, // 绑定到 actnum
          });
        } else {
          wx.showToast({ title: "订单获取失败", icon: "error" });
        }
      },
      fail: (err) => {
        console.error("订单详情请求失败：", err);
        wx.showToast({ title: "网络错误", icon: "error" });
      },
    });
  },
});
